<template>
	<app-page>
		<wd-config-provider :theme="theme">
			<view class="container">
				<view class="form">
					<wd-form ref="formRef" :model="formData" :rules="rules">
						<wd-picker :rules="rules.category_id"
							custom-class="wd-picker-custom-class-fd-col square bg-transparent" clearable
							prop="category_id" value-key="id" label-key="title" v-model="formData.category_id"
							:columns="caseTypeList" label="选择咨询方向" />
						<!-- 	<view class="consult-type" v-if="!isIndex">
							<view class="consult-type-label">咨询类型</view>
							<view class="consult-type-value" @click="setConsultType">
								<view class="tag">
									<view class="icon">
										<text class="iconfont icon-paixu"></text>
									</view>
									{{ consultType === 1?"切换为图文咨询":"切换为电话咨询" }}
								</view>
							</view>
						</view> -->
						<wd-picker :rules="rules.ask_type_id" v-if="!isIndex"
							custom-class="wd-picker-custom-class-fd-col square bg-transparent" clearable
							prop="ask_type_id" value-key="id" label-key="title" v-model="formData.ask_type_id"
							:columns="serviceList" label="咨询类型" @confirm="askTypeConfirm" />
						<view class="consult-info" v-if="formData.ask_type_id">
							<view class="type">
								<text :class="'iconfont '+ consultNameIcon[consult.title]"></text>
								<view class="text">{{ consult.title }}</view>
							</view>

							<view class="info" v-if="consult.price>0">
								<view>
									<view>￥</view>
									<view>{{ consult.price }}</view>
								</view>
								<view>{{ consult.minutes }}分钟</view>
							</view>
						</view>
						<view class="explain" v-if="consult.desc">
							<view class="arrow"></view>
							<view class="info">
								<mp-html :content="consult.desc" />

								<!-- 电话咨询介绍:
								<br />
								1、急速响应，高效沟通，直接电话连线律师，适合问题比较紧急的情况。
								<br />
								2、订单有效期 <text>60</text>分钟，<text>60</text>分钟内可随时拨打电话,电话通话时长累计不超过<text>60</text>分钟。
								<br />
								3、通话前，可先与律师确认通话时间。
								<br />
								4、若订单有效期内未与律师电话通话，可申请退款。 -->
							</view>
						</view>
					</wd-form>
				</view>
				<view class="protocol">
					<wd-checkbox checked-color="rgba(201, 28, 31, 1)" :modelValue="protocol" @change="checkboxChange"
						shape="square">
						请阅读并同意
						<text class="wd-button-custom-class-link" @click="goProtocolPage">《购买须知》</text>
					</wd-checkbox>
				</view>
				<view class="footer" id="footer">
					<view class="btns">
						<wd-button type="success" @click="submit"
							custom-class="wd-button-custom-class-my-success  wd-button-custom-class-w100">立即支付</wd-button>
					</view>
				</view>
			</view>
		</wd-config-provider>
	</app-page>
</template>

<script lang="ts">
	import { defineComponent, ref, computed } from 'vue';

	import { onLoad } from '@dcloudio/uni-app';

	import { useAppStore, useImStore } from "@/store";
	import { getTypeDetail, submitOrder, getCateList, payment, queryPayStatus, queryAssignLawyer, getProfileById } from "@/api/index.ts"
	import useRouter from '@/hooks/useRouter';

	export default defineComponent({
		name: '',
		components: {},
		setup(props, ctx) {
			// 日间light、夜间dark主题
			const theme = ref('light');
			const router = useRouter();
			const appStore = useAppStore();
			const caseTypeList = ref([]);

			const imStore = useImStore();


			const consultType = ref(1); // 咨询类型选择结果
			const protocol = ref(false); // 协议勾选状态
			// 协议勾选状态切换方法
			const checkboxChange = (e : { value : boolean }) => {
				protocol.value = e.value;
			}
			// 前往协议页面
			const goProtocolPage = () => {
				router.push({
					url: "/commonPage/protocol/protocol",
					params: {
						title: "购买须知",
					},
				})
			}
			const setConsultType = () => {
				consultType.value = consultType.value == 1 ? 2 : 1
			}
			const consultNameIcon = {
				"免费咨询": "icon-xiaoxi",
				"电话咨询": "icon-24gf-phoneBubble",
				"图文咨询": "icon-tuwenshibie",
				"合同审查": "icon-querenhetongquerenhetongqueding",
				"文书代笔": "icon-wj-ws",
				"法律顾问": "icon-fuwuguwen",
			}
			const formRef = ref(null)
			const rules = ref({
				category_id: [
					{
						required: true,
						message: '请选择咨询方向',
					}
				],
				ask_type_id: [
					{
						required: true,
						message: '请选择咨询类型',
					}
				],

			})
			const formData = ref({
				category_id: null,
				ask_type_id: null,
			})
			const consult = ref({
				desc: null,
			});
			const lawyer = ref(0);
			const isIndex = ref(false);

			const serviceList = computed(() => {
				return appStore.consultList.map((item : any, index : any) => {
					return {
						...item,
						name: item.title,
						desc: item.desc,
					}
				})
			})
			const askTypeConfirm = (e) => {
				getTypeDetail({
					id: formData.value.ask_type_id,
				}).then(res => {
					consult.value = res;
				});
			}
			onLoad((params : any) => {
				// 获取案件分类
				getCateList().then((res : any) => {
					caseTypeList.value = res;
				})
				if (!params.lawyer) {
					isIndex.value = true;
				} else {
					lawyer.value = params.lawyer
				}
				if (params.consult) {
					consult.value = appStore.getConsult(Number(params.consult));
					formData.value.ask_type_id = Number(params.consult);
					getTypeDetail({
						id: params.consult,
					}).then(res => {
						consult.value = res;
					});
				}
			})
			// 创建订单
			const submit = () => {
				if (!protocol.value) {
					uni.$wdToast.error("请先同意协议")
				}
				formRef.value.validate().then(({ valid, errors }) => {
					if (valid) {
						submitOrder({
							ask_type_id: consult.value.id,
							lawyer_id: lawyer.value,
							is_agreen: 1,
							...formData.value,
						}).then(res => {
							doPayment(res.order_id);
						});
					}
				})

			}
			// 去去支付
			const doPayment = (orderId : any) => {
				if (consult.value.price > 0) {
					payment({ ask_order_id: orderId }).then(res => {
						getOrder(orderId);
					})
				} else {
					getOrderLawyer(orderId);
				}

			}
			// 查询订单状态
			const getOrder = (orderId : any) => {
				queryPayStatus({ ask_order_id: orderId }).then(res => {
					if (res.is_pay === 1) {
						getOrderLawyer(orderId);
					} else {
						getOrder(orderId);
					}
				})
			}
			// 获取订单律师
			const getOrderLawyer = (orderId : any) => {
				queryAssignLawyer({ ask_order_id: orderId }).then((res : any) => {
					getLawyerUuid(res.lawyer_id, orderId);
				})
			}
			const getLawyerUuid = (lawyerId : any, orderId : any) => {
				if (!lawyerId) {
					uni.$wdToast.error("当前未分配律师，请联系管理员")
					return
				}
				getProfileById({ user_id: lawyerId }).then((res : any) => {
					imStore.addFriend(res.uuid, res.uid, orderId).then(async () => {
						const friend = await imStore.toFriendChat(res.uuid, res.uid, res.uuid);
						const caseType = caseTypeList.value.find((item : any) => item.id === formData.value.category_id);
						if (caseType) {
							const dd = await imStore.sendMessage({ text: `您好，我想咨询一下关于${caseType.title}问题` }, 'text', res.uuid)
						}

						router.push({
							url: "/im/chat/chat",
							params: {
								uuid: res.uuid,
							}
						});

					}).catch((error : any) => {
						if (error.code === 30003) {
							uni.$wdToast.error("系统分配用户暂未上线，请联系管理员")
						}
					})


				})
			}
			return {
				theme,
				rules,
				formRef,
				caseTypeList,
				serviceList,
				protocol,
				checkboxChange,
				goProtocolPage,
				consultType,
				setConsultType,
				consult,
				isIndex,
				consultNameIcon,
				submit,
				formData,
				askTypeConfirm,

			};
		}
	});
</script>
<!-- #ifdef MP-WEIXIN -->
<style lang="less">
	page {
		background-color: #f2f2f2;
	}
</style>
<!-- #endif -->
<style lang="less" scoped>
	page {
		background-color: #f2f2f2;
	}

	.container {
		padding: 24rpx;

		.consult-type {
			padding: 24rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			&-label {
				font-family: PingFang;
				font-weight: 500;
				font-size: 28rpx;
				color: #010101;
			}

			&-value {
				padding: 0 12rpx;
				height: 47rpx;
				background: #FFFFFF;
				box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0, 0, 0, 0.05);
				border-radius: 24rpx;


				font-family: PingFang;
				font-weight: 500;
				font-size: 22rpx;
				color: #666666;
				display: flex;
				align-items: center;
				justify-content: space-around;

				.tag {
					display: flex;
					align-items: center;
					justify-content: space-around;

					.icon {
						width: 40rpx;
						height: 40rpx;
						background-color: #C91C1F;
						border-radius: 50rpx;
						overflow: hidden;
						display: flex;
						align-items: center;
						justify-content: center;
						color: #FFFFFF;
						transform: rotate(90deg);
						margin-right: 20rpx;
					}
				}

			}
		}

		.consult-info {
			margin: 24rpx;
			margin-top: 24rpx;
			padding: 24rpx;
			height: 158rpx;
			background: #C91C1F;
			border-radius: 14rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.type {
				font-family: PingFang;
				font-weight: 500;
				font-size: 42rpx;
				color: #FFFFFF;
				display: flex;
				align-items: center;
				justify-content: flex-start;

				.iconfont {
					font-size: 50rpx;
					margin-right: 14rpx;
				}
			}

			.info {
				display: flex;
				align-items: center;
				justify-content: flex-start;


				>view {
					display: flex;
					align-items: flex-end;
				}

				view>view:nth-child(1) {
					font-family: PingFang;
					font-weight: 500;
					font-size: 32rpx;
					color: #FFFFFF;
				}


				view>view:nth-child(2) {
					font-weight: 400;
					font-size: 60rpx;
					color: #FFFFFF;
					line-height: 58rpx;
				}

				>view:nth-child(2) {
					font-family: PingFang;
					font-weight: 400;
					font-size: 33rpx;
					color: #FFFFFF;
					margin-left: 24rpx;
				}
			}
		}

		.explain {
			margin: 24rpx;
			margin-top: 40rpx;
			padding: 24rpx;
			background: #FFFFFF;
			border-radius: 14rpx;
			position: relative;

			.arrow {
				position: absolute;
				top: -40rpx;
				left: 40rpx;
				transform: rotate(90deg);
				border-top: 20rpx transparent dashed;
				border-left: 20rpx transparent dashed;
				border-bottom: 20rpx transparent dashed;
				border-right: 20rpx #fff solid;
			}

			.info {
				font-family: PingFang;
				font-weight: 400;
				font-size: 22rpx;
				color: #666666;
				line-height: 43rpx;

				text {
					color: #C91C1F;
				}
			}
		}

		.protocol {
			position: fixed;
			bottom: 260rpx;
			margin: 0 24rpx;
			padding: 24rpx;
			width: calc(100% - 24rpx - 24rpx - 24rpx - 24rpx);
			padding-bottom: 23rpx;
			text-align: center;
			font-size: 22rpx;

			:deep(.wd-checkbox) {
				.wd-checkbox__shape {
					width: 26rpx !important;
					height: 26rpx !important;
				}

				.wd-checkbox__label {
					font-family: PingFang;
					font-weight: bold;
					font-size: 22rpx;
					color: #666666;
				}

			}

			.wd-button-custom-class-link {
				font-family: PingFang;
				font-weight: bold;
				font-size: 22rpx;
			}

		}

		.footer {
			position: fixed;
			bottom: 100rpx;
			margin: 0 24rpx;
			padding: 24rpx;
			width: calc(100% - 24rpx - 24rpx - 24rpx - 24rpx);
			left: 0rpx;

			min-height: 100rpx;
			border-radius: 21rpx 21rpx 0 0;

			.btn {
				padding: 30rpx 29rpx;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
			}
		}

	}
</style>